package com.oxygen.pt.task;

import com.oxygen.pt.mapper.PatientMapper;
import com.oxygen.pt.mapper.TreatmentStatisticsMapper;
import com.oxygen.pt.pojo.entity.TreatmentStatistics;
import com.oxygen.pt.utils.PatientStatusConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

import static com.oxygen.pt.utils.PatientStatusConstants.*;

@Component
@Slf4j
public class TreatmentDetailCreator implements ApplicationRunner {

    @Resource
    private TreatmentStatisticsMapper treatmentStatisticsMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private PatientMapper patientMapper;

    /**
     * 每天自动插入数据表
     */
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void creatDetailDaily(){
        createDetail();
    }

    public void createDetail() {
        try {
            TreatmentStatistics ts = new TreatmentStatistics();
            ts.setDate(LocalDate.now());

            ts.setPendingAssignment(patientMapper.countPatientsByStatus(REMARK_TO_ALLOCATE));
            ts.setAssigned(patientMapper.countPatientsByStatus(REMARK_TO_START));
            ts.setInTreatment(patientMapper.countPatientsByStatus(REMARK_IN_TREATMENT));
            ts.setCompleted(patientMapper.countPatientsByStatus(REMARK_COMPLETED));

            ts.setCreateTime(LocalDateTime.now());
            ts.setUpdateTime(LocalDateTime.now());

            treatmentStatisticsMapper.insertTreatmentStatistics(ts);
        } catch (DuplicateKeyException ex) {
            // 当天已存在，忽略即可
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        createDetail();
    }
}
